package com.minsf.rpc;

import com.minsf.rpc.config.RegistryConfig;
import com.minsf.rpc.config.RpcConfig;
import com.minsf.rpc.constant.RpcConstant;
import com.minsf.rpc.registry.Registry;
import com.minsf.rpc.registry.RegistryFactory;
import com.minsf.rpc.utils.ConfigUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description
 * @Author minify
 * @Date 2024/3/24 19:35
 * @Project sf-rpc
 */
@Slf4j
public class RpcApplication {

    private static volatile RpcConfig rpcConfig;

    private static final String CONFIG_FILE_PATH = "application.properties";

    public static void init(RpcConfig newRpcConfig) {
        rpcConfig = newRpcConfig;
        log.info("rpc init config = {}", rpcConfig);

        // 注册中心初始化
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);

        /*RegistryConfig registryConfig = newRpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);*/

        log.info("registry init, config = {}", registryConfig);

        // 创建并注册 Shutdown Hook JVM 退出时执行操作
        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
    }

    public static void init() {
        RpcConfig newRpcConfig = null;

        try {
            // 加载配置文件
            newRpcConfig  = ConfigUtils.localConfig(RpcConfig.class, RpcConstant.DEFAULT_CONFIG_PREFIX);

            // 设置WatchService来监听配置文件的变化
            // watchConfig(newRpcConfig);

        } catch (Exception e) {
            init(new RpcConfig());
        }

        /*RegistryConfig registryConfig = newRpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);*/

        init(newRpcConfig);
    }

    public static RpcConfig getRpcConfig() {
        if (rpcConfig == null) {
            synchronized (RpcConfig.class) {
                if (rpcConfig == null) {
                    init();
                }
            }
        }
        return rpcConfig;
    }



}
